package aws;

import java.util.*;

/**
 * 找出数组中最大的k个数
 */
public class TopKInArray {

    public List<Integer> topkInt(int[]array, int k) {

        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return (o1 - o2);
            }
        });

        for(int i=0; i < array.length; i++) {
            queue.offer(array[i]);
            if(queue.size() > k) {
                queue.poll();
            }
        }

        List<Integer> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            list.add(queue.poll());
        }
        Collections.reverse(list);
        return list;
    }

    public static void main(String[] args) {
        int array[] = new int[]{1,7,4,5,9,2,3,10,33,50,100};
        new TopKInArray().topkInt(array, 2).forEach(integer -> System.out.println(integer));
    }

}
